package com.example.etwzgzxt.view.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.example.etwzgzxt.R;
import com.example.etwzgzxt.adapter.DeviceListAdapter;
import com.example.etwzgzxt.bean.DeviceInfo;
import com.example.etwzgzxt.tool.HttpHelper;
import com.example.etwzgzxt.tool.InfoApplication;
import com.example.etwzgzxt.tool.tool;
import com.example.etwzgzxt.view.activity.DeviceMessageActivity;
import com.example.etwzgzxt.view.activity.InsertDeviceActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.message.BasicNameValuePair;

public class DeviceFragment extends Fragment {

    public static final int GET_LIST = 1;
    public static final int DELETE = 2;

    ListView listView;
    DeviceListAdapter adapter;
    List<DeviceInfo> items = new ArrayList<>();

    String deleteId = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =  inflater.inflate(R.layout.fragment_device, container, false);
        Button btn = (Button) v.findViewById(R.id.btnInsertDevice);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), InsertDeviceActivity.class));
            }
        });
        listView = (ListView) v.findViewById(R.id.listView);
        adapter = new DeviceListAdapter(getActivity(), items);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), DeviceMessageActivity.class);
                intent.putExtra("deviceCode", items.get(position).getDeviceCode());
                startActivity(intent);
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage("确认删除吗？");

                builder.setTitle("提示");

                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new BackgroundTask(DELETE).execute();
                        deleteId = items.get(position).getId();
                        dialog.dismiss();

                    }
                });

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                return true;
            }
        });


        return v;
    }


    public class BackgroundTask extends AsyncTask<Void, Void, String> {

        int type;

        public BackgroundTask(int type) {
            this.type = type;
        }

        @Override
        protected String doInBackground(Void... params) {
            if ( tool.isNetworkAvailable(getActivity().getApplicationContext())) {
                if (type == GET_LIST) {
                    return getList(this);
                } else {
                    return delete(this);
                }
            }
            return  null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            parseResult(result, type);
        }
    }

    public String getList(BackgroundTask task) {
        String baseURL =   ((InfoApplication)getActivity(). getApplicationContext()).getBasehost()+"/device/getdevicelist.do";
        NameValuePair pair[] = new NameValuePair[1];
        pair[0] = new BasicNameValuePair("access_token", ((InfoApplication) getActivity().getApplication()).getAccess_token());
        List<NameValuePair> pairList = new ArrayList<>();
        Collections.addAll(pairList, pair);
        for (NameValuePair pairs: pairList) {
            System.out.println(pairs.getName()+" "+pairs.getValue());
        }

        return new HttpHelper().post(baseURL, pairList);
    }

    public String delete(BackgroundTask task) {
        String baseURL =   ((InfoApplication)getActivity(). getApplicationContext()).getBasehost()+"/device/delete.do";
        NameValuePair pair[] = new NameValuePair[2];
        pair[0] = new BasicNameValuePair("access_token", ((InfoApplication) getActivity().getApplication()).getAccess_token());
        pair[1] = new BasicNameValuePair("deviceid", deleteId);
        List<NameValuePair> pairList = new ArrayList<>();
        Collections.addAll(pairList, pair);
        for (NameValuePair pairs: pairList) {
            System.out.println(pairs.getName()+" "+pairs.getValue());
        }
        return new HttpHelper().post(baseURL, pairList);
    }

    public void parseResult(String result, int type) {
        if (result == null) {
            Toast.makeText(getActivity(), "请检查网络设置", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(result);
            switch (jsonObject.getInt("code")) {
                case 200:
                    if (type == GET_LIST) {
                        try {
                        jsonObject = new JSONObject(jsonObject.getString("result"));
                        JSONArray jsonArray = new JSONArray(jsonObject.getString("device"));
                        int length = jsonArray.length();
                        items.clear();
                        for (int i = 0; i < length; i++) {
                            jsonObject = jsonArray.getJSONObject(i);
                            items.add(new DeviceInfo(jsonObject.optString("devicecode"), jsonObject.optString("holder"), jsonObject.optString("deviceid"), jsonObject.optString("devicename")));
                        }
                        for (DeviceInfo item : items) {
                            System.out.println(item.toString());
                        }
                        adapter.updateData(items);
                        } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    } else {
                            Toast.makeText(getActivity(),"删除成功",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 403:
                 //   startActivity(new Intent(getActivity(), LoginActivity.class));
                    Toast.makeText(getActivity(), "Not Acceptable", Toast.LENGTH_SHORT).show();
                    break;
                case 406:
                    Toast.makeText(getActivity(), "Forbidden", Toast.LENGTH_SHORT).show();
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
   ;


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden) {
           new BackgroundTask(GET_LIST).execute();
        }
    }
}
